package com.canaan.common.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.PublicKey;
import java.time.LocalDate;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

public class LicenseValidator {

    public static final String AES = "AES";

    public static Map<String, String> decryptLicense(byte[] encryptedLicense) throws Exception {
        // 解密 license
        InputStream publicKeyIs = LicenseValidator.class.getClassLoader().getResourceAsStream(StringUtils.unicodeToChar("\\u0070\\u0075\\u0062\\u006c\\u0069\\u0063\\u004b\\u0065\\u0079\\u002e\\u006b\\u0065\\u0079"));

        PublicKey publicKey = EncryptDecrypt.getPublicKey(readAllBytes(publicKeyIs));

        byte[] decryptedData = EncryptDecrypt.decryptDataWithPublicKey(Base64.getDecoder().decode(encryptedLicense), publicKey);

        String licenseData = new String(decryptedData, StandardCharsets.UTF_8);

        // 解析 license 数据
        Map<String, String> licenseInfo = new HashMap<>();
        String[] lines = licenseData.split("\n");
        for (String line : lines) {
            String[] parts = line.split(":");
            if (parts.length == 2) {
                licenseInfo.put(parts[0], parts[1]);
            }
        }
        return licenseInfo;
    }

    public static boolean isValidLicense(Map<String, String> licenseInfo) {
        // 根据业务逻辑检查许可证是否有效
        // 这里可以根据实际情况进行自定义的有效性检查，比如检查序列号、过期日期等
        String machineId = licenseInfo.get("machineId");
        String macId = LicenseUtil.getMotherboardInfo();
        if(!machineId.equals(macId)){
            return false;
        }
        // 这里简单起见，只检查许可证是否为空
        return !licenseInfo.isEmpty();
    }

    public static boolean isExpired(Map<String, String> licenseInfo) {
        // 获取过期日期
        String expirationDateStr = licenseInfo.get("expirationDate");
        if (expirationDateStr != null) {
            LocalDate expirationDate = LocalDate.parse(expirationDateStr);
            // 检查过期日期是否在当前日期之后
            return LocalDate.now().isAfter(expirationDate);
        }
        // 如果没有过期日期，则认为未过期
        return false;
    }

    public static boolean isAuthorization() {
        // 读取 license.key 文件
        try {
            InputStream inputStream = LicenseValidator.class.getClassLoader().getResourceAsStream(StringUtils.unicodeToChar("\\u006c\\u0069\\u0063\\u0065\\u006e\\u0073\\u0065\\u002e\\u006b\\u0065\\u0079"));
            byte[] encryptedLicense = readAllBytes(inputStream);
            // 解密 license
            Map<String, String> licenseInfo = decryptLicense(encryptedLicense);
            // 检查许可证是否有效
            if (isValidLicense(licenseInfo)) {
                // 检查许可证是否过期
                if (isExpired(licenseInfo)) {
                    System.out.println(StringUtils.unicodeToChar("\\u8bb8\\u53ef\\u8bc1\\u4e66\\u5df2\\u8fc7\\u671f\\uff0c\\u673a\\u5668\\u7801\\uff1a") + LicenseUtil.getMotherboardInfo());
                    return false;
                }
            } else {
                System.out.println(StringUtils.unicodeToChar("\\u8bb8\\u53ef\\u8bc1\\u4e66\\u65e0\\u6548\\uff0c\\u673a\\u5668\\u7801\\uff1a") + LicenseUtil.getMotherboardInfo());
                return false;
            }
        } catch (Exception e) {
            System.out.println(StringUtils.unicodeToChar("\\u8bf7\\u5148\\u83b7\\u53d6\\u6388\\u6743\\uff0c\\u673a\\u5668\\u7801\\uff1a") + LicenseUtil.getMotherboardInfo());
            return false;
        }
        return true;
    }

    private static byte[] readAllBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            result.write(buffer, 0, length);
        }
        return result.toByteArray();
    }
}
